package com.cin.cma.client.config;

import cn.hutool.setting.Setting;
import com.alibaba.fastjson2.JSONObject;
import com.cin.cma.client.model.DataCinema;
import com.cin.cma.client.service.IConnectionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Slf4j
@Component
public class SocketIOConfig {
    public static final JSONObject info = new JSONObject();
    static final String USER_DIR = System.getProperty("user.dir");
    static final Setting SETTING = new Setting(USER_DIR + "/version.yml", true);
    @Value("${version}")
    private String version;
    @Autowired
    private IConnectionService dataBaseService;

    @PostConstruct
    public void onConnection() {
        try {
            SETTING.putByGroup("version", "system", version);
            SETTING.putByGroup("cinema_code", "system", "no");
            SETTING.putByGroup("online", "system", "N");
            info.put("version", version);
            info.put("cinemaCode", "no");
            info.put("online", "N");
            SETTING.store();
            //获取本地影院信息
            DataCinema cinemaInfo = this.dataBaseService.getLocalCinema();
            SETTING.putByGroup("cinema_code", "system", cinemaInfo.getCinemaCode());
            SETTING.putByGroup("cinema_link_id", "system", cinemaInfo.getCinemaLinkId());
            info.put("cinemaCode", cinemaInfo.getCinemaCode());
            info.put("cinemaLinkId", cinemaInfo.getCinemaLinkId());
            SETTING.store();
            cinemaInfo.setVersion(version);
            //检查客户端是否授权
            log.info("检查客户端是否授权");
            this.dataBaseService.checkAuth(cinemaInfo);
            //与Socket建立连接
            log.info("与Socket建立连接-开始");
            this.dataBaseService.onConnectionSocket(cinemaInfo.getCinemaLinkId());
            log.info("与Socket建立连接-完毕");
            SETTING.putByGroup("online", "system", "Y");
            info.put("online", "Y");
            SETTING.store();
        } catch (Exception e) {
            log.error("初始化SocketIOConfig异常", e);
        }
    }

}
